package com.ejlchina.tool.view

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.ejlchina.tool.extension.toPx

class GridItemDecoration(private val columnCount: Int, private val horizontalSpace: Int, private val verticalSpace: Int): RecyclerView.ItemDecoration() {
    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        super.getItemOffsets(outRect, view, parent, state)
        val position = parent.getChildAdapterPosition(view)
        val itemHorizontalSpace = parent.context.toPx(horizontalSpace).toInt() / 2
        outRect.left = parent.context.toPx(horizontalSpace).toInt() / 2
        outRect.right = parent.context.toPx(horizontalSpace).toInt() / 2

        when (position % columnCount) {
            0 -> {
                outRect.left = 0
                outRect.right = itemHorizontalSpace
            }
            columnCount - 1 -> {
                outRect.left = itemHorizontalSpace
                outRect.right = 0
            }
            else -> {
                outRect.left = itemHorizontalSpace
                outRect.right = itemHorizontalSpace
            }
        }

        if (position >= columnCount){
            outRect.top = parent.context.toPx(verticalSpace).toInt()
        }
    }
}